package com.cskaoyan.service.wx;

import com.cskaoyan.bean.Coupon;
import com.cskaoyan.bean.CouponExample;
import com.cskaoyan.bean.CouponUser;
import com.cskaoyan.bean.CouponUserExample;
import com.cskaoyan.controller.wx.CouponRespVo;
import com.cskaoyan.mapper.CouponMapper;
import com.cskaoyan.mapper.CouponUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author WeitenHong
 * @date 2020/10/8 15:03
 */
@Service
public class WxCouponUserServiceImpl implements WxCouponUserService {

    @Autowired
    CouponUserMapper couponUserMapper;

    @Autowired
    CouponMapper couponMapper;

    @Override
    public CouponRespVo receive(Integer userId, Integer couponId) {
        CouponRespVo couponRespVo = new CouponRespVo();
        CouponUserExample couponUserExample = new CouponUserExample();
        couponUserExample.createCriteria().andUserIdEqualTo(userId)
                .andCouponIdEqualTo(couponId);
        List<CouponUser> couponUsers = couponUserMapper.selectByExample(couponUserExample);
        if(couponUsers.size()!=0){
            couponRespVo.setErrno(740);
            couponRespVo.setErrmsg("优惠券已经领取过");
            return couponRespVo;
        }
        Coupon coupon = couponMapper.selectByPrimaryKey(couponId);
        CouponUser couponUser = new CouponUser();
        couponUser.setUserId(userId);
        couponUser.setStartTime(new Date());

        Short days = coupon.getDays();
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DAY_OF_MONTH,+days);
        couponUser.setEndTime(instance.getTime());

        couponUser.setCouponId(couponId);

        couponUserMapper.insertSelective(couponUser);
        couponRespVo.setErrmsg("成功");
        couponRespVo.setErrno(0);
        return couponRespVo;
    }
}
